package com.andy.utils;

import android.os.Build;
import android.os.Environment;
import android.util.Log;

import com.andy.MyApplication;

import java.io.File;
import java.util.Objects;

/**
 * Created by Andy on  2024/4/24 1:03
 * Email: 963069079@qq.com
 */
public class FilesUtil {
    public static final String dir = "/andyFiles/coin";
    public static final String DB = "db";

    /**
     * 判断SDCard是否存在 [当没有外挂SD卡时，内置ROM也被识别为存在sd卡]
     *
     * @return
     */
    public static boolean isSdCardExist() {
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }
    /**
     * 获取SD卡根目录路径
     *
     * @return
     */
    public static String getSdCardPath() {
//        boolean exist = isSdCardExist();
//        String sdpath = "";
//        if (exist) {
//            sdpath = Environment.getExternalStorageDirectory()
//                    .getAbsolutePath();
//        } else {
//            sdpath = "不适用";
//        }
//        return sdpath;

        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);// 判断sd卡是否存在
        if (sdCardExist) {
            if (Build.VERSION.SDK_INT>=29){
                //Android10之后
//                sdDir = MyApplication.getApplication().getExternalFilesDir(null);
//                sdDir = MyApplication.getApplication().getExternalFilesDir(Environment.DIRECTORY_DCIM);
                File externalFileRootDir = MyApplication.getApplication().getExternalFilesDir(null);
                do {
                    externalFileRootDir = Objects.requireNonNull(externalFileRootDir).getParentFile();
                } while (Objects.requireNonNull(externalFileRootDir).getAbsolutePath().contains("/Android"));
                String saveDir = Objects.requireNonNull(externalFileRootDir).getAbsolutePath();
                String savePath = saveDir + "/" + Environment.DIRECTORY_DCIM ;
                return savePath;
            }else {
                sdDir = Environment.getExternalStorageDirectory();// 获取SD卡根目录
            }
        } else {
            sdDir = Environment.getRootDirectory();// 获取跟目录
        }
        return sdDir.toString();
    }

    public static String getAppDbPath(){
        String bb = getSdCardPath();
        File DbPath = new File(getSdCardPath()  + dir + File.separator + DB );
        if (!DbPath.exists()) {
            boolean aa = DbPath.mkdirs();
            Log.e("andy","andy_test+getAppDbPath= " + DbPath.getAbsolutePath() + ", aa = " + aa+", bb = " + bb);
        }
        return DbPath.getAbsolutePath();
    }
}
